package com.yxw.yxnet_cd_center.common.utils;

import com.yxw.yxnet_cd_center.common.enums.CommonErrorEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

/**
 * @Description: 密码工具类，随机生成盐，使用MD5对密码和盐进行加密
 * @author: liuxin
 * @date: 2023.09.13
 */
@Slf4j
public class PasswordUtil {

    private static final String feignSecret  = "z5pSXd8c4iqlS4@Vdans*vYbW2Q";
    /**
     * 生成含有随机盐的密码，加密用这个方法
     */
    public static String encrypt(String password) {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(16);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = sb.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sb.append("0");
            }
        }
        String salt = sb.toString();
        password = md5Hex(password + salt);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return new String(cs);
    }

    /**
     * 生成含有随机盐的密码，加密用这个方法
     */
    public static String encryptRandom6Cahr(String password) {
        String salt = UUID.randomUUID().toString().replaceAll("-", "").substring(4, 10);
        password = salt.concat(md5Hex(password));
        return password;
    }

    /**
     * 校验密码是否正确
     */
    public static boolean verify(String verifyPwd, String md5Str) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i += 3) {
            cs1[i / 3 * 2] = md5Str.charAt(i);
            cs1[i / 3 * 2 + 1] = md5Str.charAt(i + 2);
            cs2[i / 3] = md5Str.charAt(i + 1);
        }
        String salt = new String(cs2);
        return md5Hex(verifyPwd + salt).equals(new String(cs1));
    }

    /**
     * 对用户手机号和密码进行sha1加密
     * userPassWord RSA解密后是md5
     */
    public static String signUserPassword(Long userId, String userPassWord) {
        try {
            String encryptPassword = RSAUtil.privateDecrypt(userPassWord, RSAUtil.getPrivateKey(RSAKeyUtil.PrivateKeyStr));
            SortedMap<String, Object> sortedMap = new TreeMap<>();
            sortedMap.put("userId", userId);
            sortedMap.put("userPassWord", encryptPassword);
            String signMapLinkStr = SHASignUtil.mapLink(sortedMap);
            String sign = SHASignUtil.SHA1Hex(signMapLinkStr);
            return sign;
        } catch (Exception e) {
            log.error("RSA解密失败,当前用户id:{},错误信息:{}", userId, e.getMessage());
            throw new BaseException(CommonErrorEnum.RSA_PRIVATE_DECODE_EXCEPTION);
        }
    }

    public static String signUserDefaultPassword(Long userId, String userPassWord) {
        try {
            String md5HexPassWord = PasswordUtil.md5Hex(userPassWord);
            String publicEncryptMd5HexPassWord = RSAUtil.publicEncrypt(md5HexPassWord, RSAUtil.getPublicKey(RSAKeyUtil.PublicKeyStr));
            String dbPassword = signUserPassword(userId, publicEncryptMd5HexPassWord);
            return dbPassword;
        } catch (Exception e) {
            log.error("RSA加密失败,当前用户id:{},错误信息:{}", userId, e.getMessage());
            throw new BaseException(CommonErrorEnum.RSA_PUBLIC_ENCRYPT_EXCEPTION);
        }
    }

    /**
     * 获取十六进制字符串形式的MD5摘要，这个加密不带盐
     */
    public static String md5Hex(String src) {
        log.info("签名排序内容：{}", src);
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }
    public static String getFeignSign(String userId,Long operateTime)
    {
        //"操作签名signature=md5({auditUser}&feignsecret={feignsecret}&{updateTime})"
        return md5Hex(userId + "&feignsecret=" + feignSecret + operateTime);
    }
}
